package service

import (
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model/req"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type ServicePublic struct{}

var ServicePublicInstance = new(ServicePublic)

func (service *ServicePublic) BannerCreate(request req.BannerCreateReq) (err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		err = db.Transaction(func(tx *gorm.DB) error {
			txErr := tx.Create(&request.Banner).Error
			if txErr != nil {
				return txErr
			}
			return nil
		})
	})
	return
}

func (service *ServicePublic) BannerUpdateForMap(info map[string]interface{}) (err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		err = db.Transaction(func(tx *gorm.DB) error {
			var old model.Banner
			var txErr error
			if errors.Is(tx.Where("id = ?", info["id"]).First(&old).Error, gorm.ErrRecordNotFound) {
				txErr = errors.New("原记录不存在")
			}
			if txErr != nil {
				return txErr
			}

			delete(info, "updated_at")
			txErr = tx.Model(&old).Omit("id", "created_at", "deleted_at").Updates(info).Error
			if txErr != nil {
				return txErr
			}

			return nil
		})

	})
	return err
}

func (service *ServicePublic) DeleteBannerList(info req.IdsReq) (err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		var tmpList []model.Banner
		err = db.Model(&model.Banner{}).Where("id in ?", info.Ids).Find(&tmpList).Delete(&tmpList).Error
	})
	return
}

func (service *ServicePublic) GetBannerList(info req.BannerListReq) (list interface{}, total int64, err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		limit := info.PageSize
		offset := info.PageSize * (info.Page - 1)
		var tempDb = db
		if info.ID != 0 {
			tempDb = tempDb.Where("id = ?", info.ID)
		}
		if info.Title != "" {
			tempDb = tempDb.Where("camp_name LIKE ?", "%"+info.Title+"%")
		}
		if info.Status != 0 {
			tempDb = tempDb.Where("status = ?", info.Status)
		}
		var tmpList []model.Banner
		err = tempDb.Model(&model.Banner{}).Count(&total).Error
		if err != nil {
			return
		}
		err = tempDb.Model(&model.Banner{}).Offset(offset).Limit(limit).Find(&tmpList).Error
		if err != nil {
			return
		}
		list = tmpList
	})
	return
}

func (service *ServicePublic) BannerList() (list interface{}, err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		var tmpList []model.Banner
		err = db.Model(&model.Banner{}).Find(&tmpList).Order("weight").Error
		if err != nil {
			return
		}
		list = tmpList
	})
	return
}
